<template>
  <div id="container">
    <el-tabs v-model="editableTabsValue" type="card" closable class="demo-tabs" @tab-change="handleTabsChange"
    @tab-remove="handleTabsRemove">
    <el-tab-pane v-for="item in editableTabs" :label="item.title" :name="item.path">
    </el-tab-pane>
  </el-tabs>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { TabPaneName } from 'element-plus'
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router'
import { useCookies } from '@vueuse/integrations/useCookies'
import { useDraggable } from 'vue-draggable-plus'
let cookies = useCookies()
let route = useRoute()
let router = useRouter()
const editableTabsValue = ref(route.path)
const editableTabs = ref([
  {
    title: '首页',
    path: '/Welcome'
  }
])
// 点击左侧菜单出发该方法，路由守卫添加路由
onBeforeRouteUpdate((to, _from) => {
  // console.log('onBeforeRouteUpdate', to, from);
  addTab({
    title: to.meta.title,
    path: to.path
  })
})
//新增tab
const addTab = (targetName: any) => {
  // console.log(targetName);
  let tabNum = editableTabs.value.findIndex((item) => {
    //使添加的菜单高亮
    editableTabsValue.value = targetName.path
    return item.path === targetName.path
  })
  // 如果tabNum不等于-1，说明该tab已经存在
  if (tabNum === -1) {
    editableTabsValue.value = targetName.path
    editableTabs.value.push(targetName)
    cookies.set('tabName', editableTabs.value)
  }
}
//点击改变tab
const handleTabsChange = (targetName: any) => {
  // console.log('targetName', targetName);
  router.push(targetName)
}
// 初始化tab
const initTab = () => {
  let tabName = cookies.get('tabName')
  editableTabs.value = tabName || editableTabs.value
}
initTab()
//删除tab
const handleTabsRemove = (targetName: TabPaneName | undefined) => {
  const tabs = editableTabs.value
  let activeName = editableTabsValue.value

  // 如果关闭的是当前选中的tab
  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.path === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeName = nextTab.path
        } else {
          // 如果没有其他tab了，默认跳转到首页
          activeName = '/welcome'
        }
      }
    })
    // 路由跳转到新的激活tab
    router.push(activeName)
  }
  // 更新当前激活的tab
  editableTabsValue.value = activeName
  // 从tabs列表中移除目标tab
  editableTabs.value = tabs.filter((tab) => tab.path !== targetName)
  // 更新cookie
  cookies.set('tabName', editableTabs.value)
}

useDraggable("#container .el-tabs__nav", editableTabs, {
  animation: 1000,
  onStart() {
    console.log('start')
  },
  onUpdate() {
    console.log('update')
  }
})

</script>

<style>
.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>